package com.admin.web.controller;

import com.admin.bean.AppUserContext;
import com.admin.bean.HttpResult;
import com.admin.model.AppUser;
import com.admin.repository.mongo.AppUserRepository;
import com.admin.service.EhCacheService;
import com.admin.service.EmailService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.Objects;

@RestController
@RequestMapping("/app/appUser")
public class AppUserController {

    @Resource
    private AppUserRepository appUserRepository;

    @Resource
    private EhCacheService ehCacheService;

    @Resource
    private EmailService emailService;
    @Value("${email.identifying.code.body}")
    private String emailIdentifyingCodeBody;
    @Value("${email.identifying.code.subject}")
    private String emailIdentifyingCodeSubject;

    @Value("${app.free}")
    private String appFree;

    /**
     * 邮箱和密码登陆
     *
     * @param appUser
     * @return
     */
    @RequestMapping("/emailAndPasswordLogin")
    public HttpResult<AppUser> emailAndPasswordLogin(@RequestBody AppUser appUser) {
        AppUser dbAppUser = appUserRepository.findByEmailAndPassword(appUser.getEmail(), DigestUtils.md5Hex(appUser.getPassword()));
        if (dbAppUser != null) {
            dbAppUser.setSerial(appUser.getSerial());
            appUserRepository.save(dbAppUser);
            return HttpResult.buildSuccess(dbAppUser);
        }


        return HttpResult.buildFail("密码或者账号错误!");
    }

    @RequestMapping("isAllopatry")
    public HttpResult<Void> isAllopatry(@RequestBody AppUser appUser) {
        AppUser dbAppUser = appUserRepository.findOne(appUser.getId());
        if (StringUtils.isNotEmpty(dbAppUser.getSerial())) {
            if (!Objects.equals(appUser.getSerial(), appUser.getSerial())) {
                return HttpResult.buildFail("您的账号已在其他设备登陆!");
            }
        }else{
            dbAppUser.setSerial(appUser.getSerial());
            appUserRepository.save(dbAppUser);
        }
        return HttpResult.buildSuccess(null);
    }


    @RequestMapping("/updatePassword")
    public HttpResult<Void> updatePassword(@RequestBody JSONObject jsonObject) {
        String email = jsonObject.getString("email");
        String password = jsonObject.getString("password");
        String checkCode = jsonObject.getString("checkCode");
        String validateCode = ehCacheService.getValidateCode(email);
        AppUser byEmail = appUserRepository.findByEmail(email);
        if (byEmail == null) {
            return HttpResult.buildFail("邮箱未注册");
        }
        if (!checkCode.equals(validateCode)) {
            return HttpResult.buildFail("验证码输入错误!");
        }
        byEmail.setPassword(DigestUtils.md5Hex(password));
        appUserRepository.save(byEmail);
        return HttpResult.buildSuccess(null);
    }

    /**
     * 是否过期
     *
     * @return
     */
    @RequestMapping("/isExpire")
    public HttpResult<Void> isExpire() {
        AppUser appUser = AppUserContext.getAppUser();
        appUser = appUserRepository.findOne(appUser.getId());
        if (System.currentTimeMillis() > appUser.getMemberExpire()) {
            return HttpResult.buildFail("会员已经过期");
        }
        return HttpResult.buildSuccess(null);

    }


    /**
     * 发送邮箱验证码
     *
     * @param email
     * @param version 0:注册   1:忘记密码
     * @return
     */
    @RequestMapping("/sendEmailCheckCode")
    public HttpResult<Void> sendEmailCheckCode(@RequestBody JSONObject jsonObject) {
        String email = jsonObject.getString("email");

        //找回密码
        if (jsonObject.getInteger("version") == 1) {
            AppUser byEmail = appUserRepository.findByEmail(email);
            if (byEmail == null) {
                return HttpResult.buildFail("该账号未注册!");
            }
        }
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 10000));
        String body = MessageFormat.format(emailIdentifyingCodeBody, code);
        ehCacheService.setValidateCode(email, code);
        emailService.sendSimpleMail(email, emailIdentifyingCodeSubject, body);
        return HttpResult.buildSuccess(null);
    }


    @RequestMapping("getInfo")
    public HttpResult<AppUser> getInfo(@RequestBody AppUser appUser) {
        return HttpResult.buildSuccess(appUserRepository.findOne(appUser.getId()));
    }

    @RequestMapping("/emailRegister")
    public HttpResult<Void> emailRegister(@RequestBody JSONObject jsonObject) {
        String email = jsonObject.getString("email");
        String password = jsonObject.getString("password");
//        String code = jsonObject.getString("code");
        AppUser byEmail = appUserRepository.findByEmail(email);
        if (byEmail != null) {
            return HttpResult.buildFail("该邮箱已注册!");
        }

        //验证码验证
//        Object validateCode = ehCacheService.getValidateCode(email);
//        if (Objects.isNull(validateCode) || Objects.isNull(code)) {
//            return HttpResult.buildFail("请先获取验证码!");
//        }
//        if (!code.equals(validateCode)) {
//            return HttpResult.buildFail("验证码错误!");
//        }
        AppUser appUser = new AppUser();
        appUser.setEmail(email);
        appUser.setPassword(DigestUtils.md5Hex(password));
        appUser.setRegisterTime(System.currentTimeMillis());
        appUser.setNickname(email);
        appUser.setMemberExpire(System.currentTimeMillis() + Long.valueOf(appFree));
        appUserRepository.save(appUser);
        return HttpResult.buildSuccess(null);
    }
}
